package com.hhf.riceshopping.ware.service.impl;

import com.hhf.common.constant.WareConstant;
import com.hhf.riceshopping.ware.entity.PurchaseDetailEntity;
import com.hhf.riceshopping.ware.service.PurchaseDetailService;
import com.hhf.riceshopping.ware.service.WareSkuService;
import com.hhf.riceshopping.ware.vo.MergeVo;
import com.hhf.riceshopping.ware.vo.PurchaseDoneVo;
import com.hhf.riceshopping.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhf.common.utils.PageUtils;
import com.hhf.common.utils.Query;

import com.hhf.riceshopping.ware.dao.PurchaseDao;
import com.hhf.riceshopping.ware.entity.PurchaseEntity;
import com.hhf.riceshopping.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService detailService;

    @Autowired
    WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        //如果有这个采购单id就直接合并到这个采购单身上，如果没有这个采购单就需要新建一个采购单
        if (purchaseId == null){  //新建的采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }  //如果有采购单了，那么就一定要确认合并的这个采购单是0或者1才可以合并
        //无论采购单为不为空，最终都要进行合并
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            //修改采购需求
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(i);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        detailService.updateBatchById(collect);
        //修改采购单的时间
        PurchaseEntity entity = new PurchaseEntity();
        entity.setId(purchaseId);
        entity.setUpdateTime(new Date());
        this.updateById(entity);
    }

    /**
     *
     * @param ids  采购单的id
     */
    @Override
    public void received(List<Long> ids) {
        //确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            //查询采购单的详细信息
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(item -> {
            //判断采购单状态是新建或者是已分配的才能够领取采购单
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            } else {
                return false;
            }
        }).map(item->{
            //设置最新的已领取状态
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        //2、批量改变采购单的状态
        this.updateBatchById(collect);

        //3、改变采购项的状态 ,也就是每一个采购单里边的采购项进行一个改变
        collect.forEach(item->{
            //查询出当前采购单所有的采购项
           List<PurchaseDetailEntity> entities = detailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> detailEntities = entities.stream().map(entity -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(entity.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            detailService.updateBatchById(detailEntities);
        });
    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {
        Long id = doneVo.getId();
        //利用采购单id查询出采购单的详情然后按照id进行更新状态

        //2.改变采购项的状态
        Boolean flag = true;//标识成功与否的标志位，默认是true采购成功的
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        List<PurchaseDetailEntity> updates = new ArrayList<>(); //收集状态
        PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
        for (PurchaseItemDoneVo item : items) {
            //分离出所有成功的采购项和不成功的采购项
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){  //说明采购失败
                flag = false;
                //设置失败状态
                detailEntity.setStatus(item.getStatus());
            }else {//采购成功，设置成功状态
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3.将成功采购的进行入库
                //查询出采购项的详细信息
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());
                //第一个参数：给哪个商品，第二个参数放到哪个仓库，第三个参数添加几个数量
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        detailService.updateBatchById(updates);

        //1.改变采购单状态，但需要根据采购项的状态走，如果所有的采购项都是成功做完，那么采购单的状态就是已完成
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);




    }

}